<script setup lang="ts">
import smsService from '@/api/modules/sms/sms.ts'
import SafeTopContainer from '@/components/SafeTopContainer/SafeTopContainer.vue'
import { useCountDown } from '@/hooks/useCountDown.ts'
import useUserStore from '@/store/modules/user.ts'
import { navigateBack } from '@/utils'
import { useToast } from 'wot-design-uni'
import { privacyPolicyText, userAgreementText } from './agreementText'

const loginFormRef = ref(null)
const loginForm = ref({
  mobilePhoneNumber: '',
  smsCode: '',
})
const agreementChecked = ref(true)
const agreementShow = ref(false)
const agreementType = ref<'user' | 'privacy'>('user')

const toast = useToast()
const btnLoading = ref(false)
const userStore = useUserStore()
const parentCustomerUuid = useInviteId().getInviteId()
const COUNTDOWN_DURATION = 300
const { countDown, isRunning, start, reset } = useCountDown(COUNTDOWN_DURATION)

const btnDisabled = computed(() => {
  return !loginForm.value.mobilePhoneNumber || !loginForm.value.smsCode
})

onLoad(() => {
  uni.login({
    provider: 'weixin',
    success: (res) => {
    },
    fail: () => {},
  })
})

function showAgreement(type: 'user' | 'privacy') {
  agreementType.value = type
  agreementShow.value = true
}

function loginSuccessHandler() {
  useInviteId().clearInviteId()
  toast.success({
    msg: '登录成功',
    duration: 1000,
    closed: () => {
      uni.reLaunch({ url: '/pages/home/index' })
    },
  })
}

async function handleSubmit() {
  if (!agreementChecked.value) {
    toast.error('请先同意用户协议和隐私政策')
    return
  }

  btnLoading.value = true
  const { code } = await uni.login({ provider: 'weixin' })
  const params = {
    ...loginForm.value,
    code,
    parentCustomerUuid,
  }
  const result = await userStore.mobileSmsLogin(params)
  if (result.code === 200) {
    loginSuccessHandler()
  }
  else {
    toast.error(`登录失败 ${result.msg}`)
  }
  if (result) {
    loginSuccessHandler()
  }
  else {
    console.log(result)
    toast.error('登录失败')
  }
  btnLoading.value = false
}

async function getSmsCode() {
  if (!loginForm.value.mobilePhoneNumber) {
    toast.error({
      msg: '请输入手机号码',
      zIndex: 99999,
    })
    return
  }

  reset()
  try {
    const res = await smsService.sendMessageCode({ mobilePhoneNumber: loginForm.value.mobilePhoneNumber })
    if (res?.code === 200) {
      toast.success('验证码已发送，请注意查收')
      start()
    }
    else {
      toast.error('验证码发送失败，请稍后重试')
    }
  }
  catch (error) {
    console.error(error)
    toast.error(`${error.message}`)
  }
}

async function getPhoneNumber(e: any) {
  try {
    const res = await uni.login({ provider: 'weixin' })
    const params = {
      code: res.code,
      encryptedData: e.encryptedData,
      iv: e.iv,
      parentCustomerUuid,
    }
    const result = await userStore.mobileLogin(params)
    if (result) {
      loginSuccessHandler()
    }
    else {
      toast.error('登录失败')
    }
  }
  catch (error) {
    console.error('微信登录失败', error)
    toast.error('微信授权失败')
  }
}
</script>

<template>
  <div class="login-page h-full w-full bg-white">
    <div class="login-container bg-top">
      <safe-top-container
        :padding-bottom="17"
        :padding-left="5"
      >
        <wd-navbar left-arrow custom-class="!bg-transparent" :bordered="false" @click-left="navigateBack" />
      </safe-top-container>
      <div class="login-box p-6">
        <div class="login-title flex flex-col items-center justify-center">
          <div class="h-15 w-15">
            <img src="@/static/logo.svg" class="h-full w-full">
          </div>
          <div class="text-black-500 mt-3 text-lg font-bold tracking-wider">
            欢迎登录体验U车查
          </div>
        </div>
        <div class="login-content mt-7">
          <wd-form ref="loginFormRef" :model="loginForm">
            <wd-input
              v-model="loginForm.mobilePhoneNumber"
              name="username"
              :no-border="true"
              placeholder="请输入手机号码" custom-class="custom-login__input"
              size="large"
              prefix-icon="phone"
              type="number"
            />
            <wd-input
              v-model="loginForm.smsCode"
              :no-border="true"
              placeholder="请输入验证码"
              custom-class="custom-login__input !mt-5"
              size="large"
              prefix-icon="secured"
              type="number"
            >
              <template #suffix>
                <wd-button
                  type="text" size="small" custom-class="relative top-[3px]"
                  :disabled="countDown < 300 && countDown > 0"
                  @click="getSmsCode"
                >
                  {{ (countDown === 300 || countDown === 0) ? '获取验证码' : `${countDown}秒后重试` }}
                </wd-button>
              </template>
            </wd-input>
            <div class="mt-10">
              <wd-button
                type="primary" size="large" block :round="false" :disabled="btnDisabled"
                :loading="btnLoading"
                @click="handleSubmit"
              >
                登录
              </wd-button>
              <wd-button
                type="primary" size="large" block custom-class="!bg-[#ECEFFF] !mt-5 !text-[#2540F3]" :round="false" open-type="getPhoneNumber"
                @getphonenumber="getPhoneNumber"
              >
                手机号快捷登录
              </wd-button>
            </div>
          </wd-form>
        </div>
      </div>

      <div class="absolute bottom-0 h-16 w-full flex justify-center text-sm">
        <wd-checkbox v-model="agreementChecked" custom-class="relative top-[2px]" />
        同意
        <wd-text type="primary" text="《用户协议》" @click="showAgreement('user')" />
        和
        <wd-text type="primary" text="《隐私政策》" @click="showAgreement('privacy')" />
      </div>
      <wd-action-sheet v-model="agreementShow" :title="agreementType === 'user' ? '用户协议' : '隐私政策'" custom-class="custom-action-sheet" custom-header-class="custom-action-sheet__header">
        <div class="h-[50vh] overflow-y-auto whitespace-pre-line px-5 text-sm">
          {{ agreementType === 'user' ? userAgreementText : privacyPolicyText }}
        </div>
      </wd-action-sheet>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  height: 45%;
}
.login-page{
  height: calc(100vh - 20rpx);
}
</style>

<style lang="scss">
.custom-login__input{
  border-radius: 8px !important;
  background: #F3F5FA !important;
  .wd-input__icon{
    background: transparent !important;
  }
  .wd-icon{
    position: relative;
    top: -2px;
  }
}
</style>

<style>
.custom-action-sheet{
  min-height: 100%;
  background-image: url('https://124.70.200.199:36552/down/S9NWKXTEUKD7.png') !important;
  background-size: cover;
  background-position: center;
}

.custom-action-sheet__header{
  font-size: 18px !important;
  font-weight: bold !important;
  line-height: 3 !important;
  height: auto !important;
}
</style>
